package com.tensquare.manager.filter;

import cn.hutool.core.util.StrUtil;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import utils.JwtUtil;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by WF on 2020/7/30 15:30
 * 后台网关过滤器
 */
@Component
public class ManagerFilter extends ZuulFilter {
    @Autowired
    private JwtUtil jwtUtil;
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        //1.得到当前请求的上下文对象
        RequestContext currentContext = RequestContext.getCurrentContext();
        //2.得到请求对象
        HttpServletRequest request = currentContext.getRequest();

        if(request.getMethod().equals("OPTIONS")){ //因为当我们发送请求到网关时是两次请求，此方法（OPTIONS）需要放行
            return null;
        }
        if(request.getRequestURL().toString().contains("/login")){
            return null;
        }
        //3.得到请求头
        String authorization = request.getHeader("Authorization");
        //4.判断
        if(authorization != null && authorization.startsWith("Bearer ")){
            //4.1)得到token的值
            String token = authorization.substring(7);
            //4.2)解析token
            Claims claims = jwtUtil.parseToken(token);
            if(claims != null){
                //4.3)得到角色
                String roles = (String) claims.get("roles");
                //4.4)必须是管理员角色（即roles=admin）才能继续
                if("admin".equals(roles)){
                    currentContext.addZuulRequestHeader("Authorization",authorization);
                    System.out.println("将我们自己的请求头添加到网关的请求头中，" + authorization);
                    return null;
                }
            }
        }
        currentContext.setSendZuulResponse(false);  //不再继续执行
        currentContext.setResponseStatusCode(403);  //设置响应的状态码是403或401
        currentContext.setResponseBody("无权访问!");//设置响应体内容
        currentContext.getResponse().setContentType("text/html;charset=utf-8"); //设置响应的内容类型
        return null;
    }
}
